#ifndef __SERVER_H__
#define __SERVER_H__

#include <QObject>
#include <QMap>
#include <QPair>
#include <QMutex>
#include <QTime>
#include <QThread>
#include <QTimer>

class Friend;

class FakeTcp;
class ServerProtocol;
class ServerConnectionAction;
class ServerChatAction;
class ServerUserAction;
class ServerFriendAction;
class Chat;

class Database;
class QTimer;

class Server : public QObject{
Q_OBJECT

public:
	Server(quint16 port);
	~Server();
private:
	friend class KeepAliveThread;
	void connectionAction(ServerConnectionAction* sca);
	void chatAction(ServerChatAction* sha);
	void userAction(ServerUserAction* sua);
	void friendAction(ServerFriendAction* sfa);

	void connect(QPair<QString, quint16> userInfo, QString login, QString password);
	void disconnect(Friend* user);
	void keepAlive(Friend* user);

	void chatStart(Friend* user, int friendId);
	void chatInvite(Friend* user, Chat* chat, int friendId);
	void chatSend(Friend* user, Chat* chat, QString message);
	void chatExit(Friend* user, Chat* chat);

	void friendInvite(Friend* user, QString login);
	void friendAccept(Friend* user, QString login);
	void friendDeny(Friend* user, QString login);
	void friendRemove(Friend* user, Friend* other);

	int nextChatId;
	QMutex chatMutex;

	QTimer* keepAliveTimer;
	quint16 port;
	FakeTcp *listenSocket;
	ServerProtocol *serverProtocol;
	Database *db;
	QMap<int, Friend *> users;
	QMap<QPair<QString, quint16>, Friend *> who;
	QMap<Friend *, FakeTcp *> where;
	QMap<int, Chat*> chats;
	QMap<Friend*, QTime*> aliveTimes;
private slots:
	void action();
	void checkKeepAlive();
};

#endif
